package cn.git.agent;

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.matcher.ElementMatchers;

import java.lang.instrument.Instrumentation;

/**
 * @description: byteBuddy探针，实现springmvc 拦截器
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-12-19
 */
public class SpringMVCAgent {

    /**
     * 控制器注解名称
     */
    public static final String REST_CONTROLLER_NAME = "org.springframework.web.bind.annotation.RestController";
    public static final String CONTROLLER_NAME = "org.springframework.stereotype.Controller";


    /**
     * premain方法,main方法执行之前进行调用，插桩代码入口
     * @param args 标识外部传递参数
     * @param instrumentation 插桩对象
     */
    public static void premain(String args, Instrumentation instrumentation) {
        // 创建AgentBuilder对象
        AgentBuilder builder = new AgentBuilder.Default()
                // 忽略拦截的包
                .ignore(ElementMatchers.nameStartsWith("net.bytebuddy")
                        .or(ElementMatchers.nameStartsWith("org.apache"))
                )
                // 拦截标注以什么注解的类
                .type(ElementMatchers.isAnnotatedWith(
                        ElementMatchers.named(CONTROLLER_NAME)
                                .or(ElementMatchers.named(REST_CONTROLLER_NAME)))
                )
                // 前面的type()方法匹配到的类，进行拦截
                .transform(new ByteBuddyTransform())
                .with(new ByteBuddyListener());

        // 安装
        builder.installOn(instrumentation);
    }

}
